Page({
  data: {
    points: 0,
    rewards: [],
    showToast: false,
    toastTitle: '',
    toastDuration: 2000,
    showOrderTicket: false,
    currentOrder: null
  },

  onLoad() {
    this.fetchUserPoints();
    this.fetchRewardsList();
  },

  // 处理401错误
  handleUnauthorized() {
    getApp().handleUnauthorized();
  },

  // 获取用户积分
  fetchUserPoints() {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.showCustomToast('请先登录');
      return;
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/point',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 401) {
          this.handleUnauthorized();
          return;
        }
        if (res.data.code === 200) {
          this.setData({
            points: res.data.data.points
          });
        } else {
          this.showCustomToast(res.data.msg || '获取积分失败');
        }
      },
      fail: () => {
        this.showCustomToast('网络错误，请稍后重试');
      }
    });
  },

  // 获取奖品列表
  fetchRewardsList() {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.showCustomToast('请先登录');
      return;
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/product/list',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 401) {
          this.handleUnauthorized();
          return;
        }
        if (res.data.code === 200) {
          const rewards = res.data.data.map(item => ({
            id: item.id,
            name: item.name,
            description: item.description,
            points: item.points,
            image: item.imageUrl,
            stock: item.stock
          }));
          this.setData({ rewards });
        } else {
          this.showCustomToast(res.data.msg || '获取奖品列表失败');
        }
      },
      fail: () => {
        this.showCustomToast('网络错误，请稍后重试');
      }
    });
  },

  // 点击奖品
  onRewardTap(e) {
    const reward = e.currentTarget.dataset.reward;
    if (this.data.points < reward.points) {
      this.showCustomToast('积分不足');
      return;
    }

    if (reward.stock <= 0) {
      this.showCustomToast('商品库存不足');
      return;
    }

    wx.showModal({
      title: '确认兑换',
      content: `确定要使用 ${reward.points} 积分兑换 ${reward.name} 吗？`,
      success: (res) => {
        if (res.confirm) {
          this.exchangeReward(reward);
        }
      }
    });
  },

  // 兑换奖品
  exchangeReward(reward) {
    const token = wx.getStorageSync('token');
    if (!token) {
      this.showCustomToast('请先登录');
      return;
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/product/exchange',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        productId: reward.id,
        remark: `兑换商品：${reward.name}`
      },
      success: (res) => {
        if (res.statusCode === 401) {
          this.handleUnauthorized();
          return;
        }
        if (res.data.code === 200) {
          this.setData({
            points: this.data.points - reward.points,
            ['rewards[' + this.data.rewards.findIndex(item => item.id === reward.id) + '].stock']: reward.stock - 1,
            showOrderTicket: true,
            currentOrder: {
              orderNo: res.data.data.orderNo || '未知订单号',
              productName: reward.name,
              points: reward.points,
              exchangeTime: this.formatTime(new Date()),
              qrCode: 'data:image/png;base64,' + res.data.data.qrCode
            }
          });
        } else {
          this.showCustomToast(res.data.msg || '兑换失败');
        }
      },
      fail: () => {
        this.showCustomToast('网络错误，请稍后重试');
      }
    });
  },

  // 格式化时间
  formatTime(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    const second = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  },

  // 关闭订单票
  closeOrderTicket() {
    this.setData({
      showOrderTicket: false,
      currentOrder: null
    });
  },

  // 保存订单票
  saveOrderTicket() {
    if (!this.data.currentOrder || !this.data.currentOrder.qrCode) {
      this.showCustomToast('订单信息不完整');
      return;
    }

    wx.showLoading({
      title: '正在保存...',
      mask: true
    });

    // 将base64图片转换为临时文件
    const base64Data = this.data.currentOrder.qrCode.replace(/^data:image\/\w+;base64,/, "");
    const fileManager = wx.getFileSystemManager();
    const filePath = `${wx.env.USER_DATA_PATH}/temp_qrcode.png`;
    
    try {
      fileManager.writeFileSync(
        filePath,
        base64Data,
        'base64'
      );

      // 保存图片到相册
      wx.saveImageToPhotosAlbum({
        filePath: filePath,
        success: () => {
          wx.hideLoading();
          this.showCustomToast('订单票已保存到相册');
        },
        fail: (err) => {
          wx.hideLoading();
          if (err.errMsg.includes('auth deny')) {
            wx.showModal({
              title: '提示',
              content: '需要您授权保存图片到相册',
              success: (res) => {
                if (res.confirm) {
                  wx.openSetting();
                }
              }
            });
          } else {
            this.showCustomToast('保存失败，请重试');
          }
        }
      });
    } catch (error) {
      wx.hideLoading();
      this.showCustomToast('生成图片失败，请重试');
    }
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack();
  },

  // 显示自定义提示
  showCustomToast(title, duration = 2000) {
    this.setData({
      showToast: true,
      toastTitle: title,
      toastDuration: duration
    });
  },

  // 提示隐藏回调
  onToastHide() {
    this.setData({
      showToast: false,
      toastTitle: ''
    });
  }
}); 